package com.share.example.classload.config;

import com.share.common.utils.FileUtil;
import com.share.example.classload.config.model.OutDirClassLoader;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


@Slf4j
//@Component
public class LoadOutDirClassConfig {
    @Value("${encryptClassDirHome}")
    private String encryptClassDirHome;

    private String encryptClassPackageDir;

    @Value("${encryptClassPackage}")
    private String encryptClassPackage;


    @PostConstruct
    public void loadClassToJvm() {
        URL[] urls = new URL[1];
        List<File> fileList = FileUtil.listFile(encryptClassDirHome);
        for (File file : fileList) {
            try {
                URL url = file.toURI().toURL();
                urls[0] = (url);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        }

        OutDirClassLoader outDirClassLoader = new OutDirClassLoader(urls);
        outDirClassLoader.loadJar(encryptClassDirHome);
        try {
            Class<?> aClass = Class.forName("com.share.example.classload.service.impl.ClassloadServiceImpl");
            aClass.newInstance();
            log.info("Fdfdfdfdfd");
        } catch (Exception e) {
            e.printStackTrace();
        }

//        outDirClassLoader.loadClass()
//        OutDirClassLoader.loadJar(encryptClassDirHome);
//        log.info("入参配置encryptClassDirHome={},encryptClassPackage={}", encryptClassDirHome, encryptClassPackage);
//        this.encryptClassPackageDir = encryptClassPackage.replaceAll("\\.", File.separator + File.separator);
//
//        log.info("###正在初始化类加载###");
//        List<File> fileList = FileUtil.listFile(encryptClassDirHome);
//        for (File file : fileList) {
//            String fileName = file.getAbsolutePath();
//            if (fileName.endsWith(".class")) {
//                boolean contains = fileName.contains(encryptClassPackageDir);
//                if (!contains) {
//                    continue;
//                }
//
//                //加密的字节码
//                byte[] enCrptyBytes = FileUtil.readByte(file);
//
//            } else if (fileName.endsWith(".jar")) {
//                Map<String, byte[]> classMap = JarFileUtil.mapJarContent(file);
//                for (Map.Entry<String, byte[]> entry : classMap.entrySet()) {
//                    String clazzName = entry.getKey();
//                    if (clazzName.endsWith(".class")) {
//                        byte[] clazzByte = entry.getValue();
//
//                    }
//                }
//            }
//        }
        log.info("###类加载完毕###");
    }
}
